package me.send.business.service.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import me.send.business.base.alipay.util.AlipayNotify;
import me.send.business.base.jpush.JPush;
import me.send.business.service.BaseService;
import me.send.business.service.bean.WxPayResult;
import me.send.business.service.cons.LevelCons;
import me.send.business.service.cons.MessageCons;
import me.send.business.service.cons.OrderCons;
import me.send.business.service.cons.ProgressCons;
import me.send.business.service.mapper.OrderMapper;
import me.send.business.service.mapper.OrderProgressMapper;
import me.send.business.service.mapper.PopuserMapper;
import me.send.business.service.mapper.UserMapper;
import me.send.business.service.mapper.WalletMapper;
import me.send.business.service.pojo.BatchWithdrawRecord;
import me.send.business.service.pojo.Message;
import me.send.business.service.pojo.OrderProgress;
import me.send.business.service.pojo.WithdrawOrder;
import me.send.framework.util.HelperUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.jpush.api.JPushClient;
@Service
public class WalletService extends BaseService {
	private final static Logger logger = LoggerFactory
			.getLogger(WalletService.class.getName());
	@Autowired
	private WalletMapper walletMapper;
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private PopuserMapper popuserMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	MessageService messageService;
	@Autowired
	OrderProgressMapper orderProgressMapper;
	
	public void buildPayRecord(Map<String, Object> param) {
		walletMapper.builePayRecord(param);
	}
	
	public List<Map<String, Object>> queryRechargeList() {
		BigDecimal fundBalance=walletMapper.queryFundPollBalance("FUND_50_WAN");
		List<Map<String, Object>> list=walletMapper.queryRechargeList();
		List<Map<String, Object>> returnList=new ArrayList<Map<String,Object>>();
		if(fundBalance.doubleValue()<=0){
			for(Map<String, Object> map:list){
				BigDecimal giveAmount=(BigDecimal)map.get("giveAmount");
				if(giveAmount.doubleValue()>0){
				}else{
					returnList.add(map);
				}
			}
			return returnList;
		}else{
			return list;
		}
	}
	
	public List<Map<String, Object>> queryRedAmountList(int userid) {
		BigDecimal fundBalance=walletMapper.queryFundPollBalance("FUND_50_WAN");
		List<Map<String, Object>> list=walletMapper.queryRedAmountList(userid);
		if(fundBalance.doubleValue()<=0){
			return null;
		}else{
			return list;
		}
	}

	private String time(String pattern) {
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		return sdf.format(new Date());
	}


	public double userBalance(int userid) {
		Object o = walletMapper.user_balance(userid);
		if (o == null) {// 数据库中没有该用户记录，新建记录
			String date = time("yyyy-MM-dd HH:mm:ss");
			Map<String, Object> p = new HashMap<String, Object>();
			p.put("createTime", date);
			p.put("userId", userid);
			walletMapper.addUserWallet(p);
			return 0;
		} else {
			return Double.parseDouble(o.toString());
		}
	}

	@SuppressWarnings({ "unused", "rawtypes" })
	public String notifyAlipayUser(ServletRequest sr) throws Exception {
		HttpServletRequest request = (HttpServletRequest) sr;
		// 获取支付宝POST过来反馈信息
		Map<String, String> params = new HashMap<String, String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"),
			// "gbk");
			params.put(name, valueStr);
		}
		// 商户订单号
		String out_trade_no = new String(request.getParameter("out_trade_no")
				.getBytes("ISO-8859-1"), "UTF-8");
		// 商户金额
		String total_fee = new String(request.getParameter("total_fee")
				.getBytes("ISO-8859-1"), "UTF-8");
		// 支付宝交易号
//		String trade_no = new String(request.getParameter("trade_no").getBytes(
//				"ISO-8859-1"), "UTF-8");
		// 交易状态
		String trade_status = new String(request.getParameter("trade_status")
				.getBytes("ISO-8859-1"), "UTF-8");
		logger.info("notify_alipay:params:"+params);
		if (AlipayNotify.verifyRSA(params)) {// 验证成功
			if (trade_status.equals("TRADE_FINISHED")
					|| trade_status.equals("TRADE_SUCCESS")) {
				Map<String, Object> hsOrderInfo = walletMapper
						.userOrderStatus(out_trade_no);
				int hsOrderStatus = (Integer) hsOrderInfo.get("status");
				int payWay = (Integer)hsOrderInfo.get("payWay");
				if (payWay==0) {// 支付方式为0，表明此为用户充值行为
					doneRechargePayment(hsOrderInfo, total_fee, out_trade_no);
				} else {// 用户直接用支付宝付款
					doneOrderPayment(hsOrderInfo, total_fee, out_trade_no);
				}
			}
			return "success";
		} else {// 验证失败
			logger.info("notify_alipay:fail verify");
			return "fail";
		}
	}
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	public void doneOrderPayment(Map<String, Object> hsOrderInfo,String total_fee,String out_trade_no){
		int hsOrderStatus = (Integer) hsOrderInfo.get("status");
		Object thisOrderId = hsOrderInfo.get("orderId");
		long redId = (Long)hsOrderInfo.get("redId");
		logger.info("done_order,in param，thisOrderId："+thisOrderId+",total_fee:"+total_fee+",out_trade_no:"+out_trade_no);
		int hsOrderId = (Integer) thisOrderId;
		if (hsOrderStatus == 0) {
			// 1,修改支付订单状态为支付成功
			walletMapper.updateUserOrderStatus(out_trade_no);
			// 2,查询呼单信息，获取该单的消费和代购额
			Map<String, Object>  temp1 = orderMapper.getOrderFeeInfo(hsOrderId);
			Integer status=(Integer)temp1.get("status");
			final Integer userid=(Integer)temp1.get("userid");
			if(status>7){//如果状态为8表示已支付
				logger.info("done_order,out param，该呼单已被支付，status："+status);
				return;
			}
			Double totalFee=Double.parseDouble(total_fee);
			double tip = (Double) temp1.get("tip");
			double fee = (Double) temp1.get("fee");
			double discount = (Double) temp1.get("discount");
			Map<String,Object> param=new HashMap<String, Object>();
			double orderTotalFee=tip+fee;
			BigDecimal giveMoney =new BigDecimal(0);
			
			if(redId==0){
			}else{
				param.put("userid", userid);
				param.put("redid", redId);
				param.put("orderid", hsOrderId);
				Map<String,Object> redMap=walletMapper.queryRedAmount(param);
				giveMoney=BigDecimal.valueOf((Double)redMap.get("money"));
				orderTotalFee=orderTotalFee-giveMoney.doubleValue();
				
			}
					
			if(orderTotalFee>totalFee){
				logger.info("done_order,out param，呼单总额与实际支付金额不一致，orderTotalFee："+orderTotalFee+",totalFee:"+totalFee);
				return;
			}
			if(redId==0){
			}else{
				param.put("userid", userid);
				param.put("redid", redId);
				param.put("orderid", hsOrderId);
				param.put("status", 2);//将优惠券改为已使用
				walletMapper.updateRed(param);
			}
			
			final int brokerid = (Integer) temp1.get("brokerid");
			int type = (Integer) temp1.get("ordertypeid");
			// 3,为经纪人钱包记录增加一条记录
			String desc = null;
				if (type == 1)
					desc = "代办";
				else if (type == 2)
					desc = "代购";
				else
					desc = "代送";
			SimpleDateFormat sdf = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss");
			String changeTime = sdf.format(new Date());
			temp1.put("purchaseAmount", fee+discount);
			temp1.put("tipAmount", tip);
			temp1.put("brokerId", brokerid);
			temp1.put("changeDesc", desc);
			temp1.put("changeTime", changeTime);
			temp1.put("orderId", hsOrderId);
			walletMapper.addBrokerWalletLog(temp1);
			// 4,给经纪人钱包增加相应的金额
			temp1 = new HashMap<String, Object>();
			temp1.put("purchaseAmount", fee+discount);
			temp1.put("tipAmount", tip);
			temp1.put("brokerid", brokerid);
			//判断经纪人钱包是否存在
			Map<String, Object> map = walletMapper.getBalance(brokerid);
			if (map == null) {
				Map<String, Object> temp = new HashMap<String, Object>();
				temp.put("popid", brokerid);
				temp.put("date", sdf.format(new Date()));
				walletMapper.addBrokerWallet(temp);
				map = walletMapper.getBalance(brokerid);
			}
			walletMapper.payToBroker(temp1);
			// 5,设置呼送订单为已完成
			temp1 = new HashMap<String, Object>();
			temp1.put("status", 8);
			temp1.put("orderid", hsOrderId);
//			int i=1/0;
			orderMapper.updateOrderStatus(temp1);
			/**
			 * -------------------------------------------------maxmin修改 判断是否更新用户等级--------------------------------------------------
			 */
			final int oid = hsOrderId;
			//判断是否需要修改用户等级
			new Thread(new Runnable() {
				public void run() {
					//推送付款成功消息
					Map<String,Object> brokerMap=popuserMapper.queryBrokerById(brokerid);
					//User user=userMapper.getUserNameById(userid);
					JPushClient clientBroker = JPush.getBrokerJPushClient();
//					JPushClient clientUser = JPush.getUserJPushClient();
//					JPush.pushWithAlias(clientUser, "", user.getIsvAccountId());
					JPush.pushWithAlias(clientBroker, OrderCons.PAY_SUCCESS, brokerMap.get("isvAccountId").toString());
					//经纪人通知存档
					Message message = new Message(OrderCons.PAY_SUCCESS, brokerid,
							MessageCons.USER_TYPE_BROKER,
							MessageCons.MESSAGE_TYPE_ORDER);
					message.setCreatetime(HelperUtil.getCurrentDate());
					message.setUpdatetime(HelperUtil.getCurrentDate());
					messageService.saveMessage(message);
					//用户通知存档
					Message usermessage = new Message(OrderCons.USER_PAY_SUCCESS, userid,
							MessageCons.USER_TYPE_USER,
							MessageCons.MESSAGE_TYPE_ORDER);
					usermessage.setCreatetime(HelperUtil.getCurrentDate());
					usermessage.setUpdatetime(HelperUtil.getCurrentDate());
					messageService.saveMessage(usermessage);
					
					//保存进度
					OrderProgress op= new OrderProgress();
					op.setUserMsg(ProgressCons.ORDER_PAYED_MSG);
					op.setContent(ProgressCons.ORDER_PAYED_CONTENT);
					op.setOrderid(oid);
					op.setOrderStatus(OrderCons.ORDER_WAIT_EVALUATE);
					op.setCreatetime(HelperUtil.getCurrentDate());
					op.setUpdatetime(HelperUtil.getCurrentDate());
					orderProgressMapper.addOrderProgress(op);
					
					Map<String, Object> countAndLevel = orderMapper.getOrderCountAndLevelById(brokerid);
					int count = (Integer)countAndLevel.get("count");
					int level = (Integer)countAndLevel.get("level");
					int lv = 0;
					if (count>=LevelCons.LEVEL_TWO_ORDERS&&count<=LevelCons.LEVEL_TEN_ORDERS) {
						lv = count/LevelCons.LEVEL_TWO_ORDERS+1;
						if (level<lv) {
							//修改经纪人的等级
							Map<String, Object> params = new HashMap<String, Object>();
							params.put("brokerid", brokerid);
							params.put("level", lv);
							popuserMapper.updateBrokerLevel(params);
						}
					}else if (count>LevelCons.LEVEL_TEN_ORDERS&&count<=LevelCons.LEVEL_FIFTY_ORDERS) {
						lv = (count-LevelCons.LEVEL_TEN_ORDERS)/LevelCons.FROM_TEN_TO_FIFTY_PER_LEVEL_ORDERS+LevelCons.LEVE_TEN;
						if (level<lv) {
							//修改经纪人的等级
							Map<String, Object> params = new HashMap<String, Object>();
							params.put("brokerid", brokerid);
							params.put("level", lv);
							popuserMapper.updateBrokerLevel(params);
						}
					}else if (count>LevelCons.LEVEL_FIFTY_ORDERS) {
						lv = (count-LevelCons.LEVEL_FIFTY_ORDERS)/LevelCons.FROM_FIFTY_TO_MORE_PER_LEVEL_ORDERS+LevelCons.LEVE_FIFTY;
						if (level<lv) {
							//修改经纪人的等级
							Map<String, Object> params = new HashMap<String, Object>();
							params.put("brokerid", brokerid);
							params.put("level", lv);
							popuserMapper.updateBrokerLevel(params);
						}
					}
				}
			}).start();
			/**
			 * -------------------------------------------------maxmin修改 判断是否更新用户等级 END--------------------------------------------------
			 */
			if(discount>0){
				Map<String,Object> pool=walletMapper.queryFundPoll("FUND_10_WAN");
				Map<String,Object> poolParam=new HashMap<String, Object>();
				poolParam.put("amount", discount);
				poolParam.put("fundCode", "FUND_10_WAN");
				walletMapper.updateActivityFundPool(poolParam);
				Map<String,Object> logParam=new HashMap<String, Object>();
				logParam.put("activityType", 0);//0表示商品折扣
				logParam.put("amount", discount);
				logParam.put("orderId", hsOrderId);
				logParam.put("createTime", Calendar.getInstance().getTime());
				logParam.put("activityDesc", "商品折扣"+discount+"元");
				logParam.put("fundId", pool.get("fundId"));
				logParam.put("fundCode", "FUND_10_WAN");
				walletMapper.insertActivityFundPoolLog(logParam);
			}
			
			if(giveMoney.doubleValue()>0){
				if((tip+fee)<giveMoney.doubleValue()){
					giveMoney=BigDecimal.valueOf(tip+fee);
				}
				Map<String,Object> pool=walletMapper.queryFundPoll("FUND_50_WAN");
				Map<String,Object> poolParam=new HashMap<String, Object>();
				poolParam.put("amount", giveMoney.doubleValue());
				poolParam.put("fundCode", "FUND_50_WAN");
				walletMapper.updateActivityFundPool(poolParam);
				Map<String,Object> logParam=new HashMap<String, Object>();
				logParam.put("activityType", 2);//0表示商品折扣
				logParam.put("amount", giveMoney.doubleValue());
				logParam.put("orderId", hsOrderId);
				logParam.put("createTime", Calendar.getInstance().getTime());
				logParam.put("activityDesc", "优惠券"+giveMoney.doubleValue()+"元");
				logParam.put("fundId", pool.get("fundId"));
				logParam.put("fundCode", "FUND_50_WAN");
				walletMapper.insertActivityFundPoolLog(logParam);
			}
			
			logger.info("done_order,out param，success，orderTotalFee："+orderTotalFee+",totalFee:"+totalFee);
			
		}
	}
	
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	public void doneRechargePayment(Map<String, Object> hsOrderInfo,String total_fee,String out_trade_no){
		// 获取用户id及充值金额
		int userid = (Integer) hsOrderInfo.get("userId");
		int hsOrderStatus = (Integer) hsOrderInfo.get("status");
		int orderId = (Integer) hsOrderInfo.get("orderId");
		// double amount = (Double) hsOrderInfo.get("amount");
		if (hsOrderStatus == 0) {
			Map<String,Object> rechargeMap=walletMapper.queryRechargeAmount(orderId);
			BigDecimal rechargeAmount=(BigDecimal)rechargeMap.get("amount");
			BigDecimal giveAmount=(BigDecimal)rechargeMap.get("giveAmount");
			int count=walletMapper.queryRechargeWalletLogCount(userid);
			if(count>0){//首次充值才送钱
				giveAmount=BigDecimal.valueOf(0);
			}
			double amount = Double.parseDouble(total_fee);
			
			// 1,修改支付订单状态为支付成功
			walletMapper.updateUserOrderStatus(out_trade_no);
			if(amount<rechargeAmount.doubleValue()){
				
			}else{
				BigDecimal addAmount=rechargeAmount.add(giveAmount);
				amount=addAmount.doubleValue();
			}
			// 2,给用户钱包记录增加新的记录
			Map<String, Object> temp = new HashMap<String, Object>();
			temp.put("userid", userid);
			temp.put("amount", amount);
			SimpleDateFormat sdf = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			String changeTime = sdf.format(new Date());
			temp.put("changeTime", changeTime);
			int changeType = 0;
			String changeDesc = "充值";
			temp.put("orderId", hsOrderInfo.get("payOrderId"));
			temp.put("changeDesc", changeDesc);
			temp.put("changeType", changeType);
			walletMapper.buildUserRecord(temp);
//			int i=1/0;
			// 3,修改用户钱包数据
			Object o = walletMapper.user_balance(userid);
			if (o == null) {// 数据库中没有该用户记录，新建记录
				String date = time("yyyy-MM-dd HH:mm:ss");
				Map<String, Object> p = new HashMap<String, Object>();
				p.put("createTime", date);
				p.put("userId", userid);
				walletMapper.addUserWallet(p);
			}
			walletMapper.updateUserWallet(temp);
			
			if(giveAmount.doubleValue()>0){
				Map<String,Object> pool=walletMapper.queryFundPoll("FUND_50_WAN");
				Map<String,Object> poolParam=new HashMap<String, Object>();
				poolParam.put("amount", giveAmount.doubleValue());
				poolParam.put("fundCode", "FUND_50_WAN");
				walletMapper.updateActivityFundPool(poolParam);
				Map<String,Object> logParam=new HashMap<String, Object>();
				logParam.put("activityType", 1);//0表示商品折扣
				logParam.put("amount", giveAmount.doubleValue());
				logParam.put("orderId", orderId);
				logParam.put("createTime", Calendar.getInstance().getTime());
				logParam.put("activityDesc", "充值送"+giveAmount.doubleValue()+"元");
				logParam.put("fundId", pool.get("fundId"));
				logParam.put("fundCode", "FUND_50_WAN");
				walletMapper.insertActivityFundPoolLog(logParam);
			}
		}
	}

	@SuppressWarnings("unused")
	public void notifyWeixinUser(WxPayResult wpr)
			throws Exception {
		logger.info("notify_weixin:notifyWeixinUser begin wpr.getTotalFee()："+wpr.getTotalFee()+",wpr.getOutTradeNo():"+wpr.getOutTradeNo());
		Double fee=Double.parseDouble(wpr.getTotalFee())/100;
		String total_fee=fee+"";
		String out_trade_no=wpr.getOutTradeNo();
		Map<String, Object> hsOrderInfo = walletMapper
				.userOrderStatus(out_trade_no);
		int hsOrderStatus = (Integer) hsOrderInfo.get("status");
		int payWay = (Integer)hsOrderInfo.get("payWay");
		if (payWay==0) {// 充值方式为0，表明此为用户充值行为
			doneRechargePayment(hsOrderInfo, total_fee, out_trade_no);
		} else {// 用户直接用微信付款
			doneOrderPayment(hsOrderInfo, total_fee, out_trade_no);
		}
		logger.info("notify_weixin:notifyWeixinUser end ");

	}
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	public String userWalletPay(int orderid,int redid) {
		Map<String, Object> orderInfo = orderMapper.getOrderFeeInfo(orderid);
		final int userid = (Integer) orderInfo.get("userid");
		int brokerid = (Integer) orderInfo.get("brokerid");
		double fee = (Double) orderInfo.get("fee");
		double tip = (Double) orderInfo.get("tip");
		double discount = (Double) orderInfo.get("discount");
		Integer status=(Integer)orderInfo.get("status");
		if(status>7){//如果状态为8表示已支付
			logger.info("done_order,out param，该呼单已被支付，status："+status);
			return "repeat";
		}
		Map<String,Object> param=new HashMap<String, Object>();
		
		int type = (Integer) orderInfo.get("ordertypeid");
		String desc = "";
		Object orderDesc = orderInfo.get("descption");
		if (orderDesc != null) {// 文字呼单
			if (type == 1) {
				desc += "代办:" + orderDesc;
			} else if (type == 2) {
				desc += "代购:" + orderDesc;
			} else {
				desc += "代送:" + orderDesc;
			}
		} else {// 语音呼单
			if (type == 1) {
				desc += "代办:语音呼单";
			} else if (type == 2) {
				desc += "代购:语音呼单";
			} else {
				desc += "代送:语音呼单";
			}
		}
		double balance = userBalance(userid);
		SimpleDateFormat adf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date = adf.format(new Date());
		BigDecimal giveMoney =new BigDecimal(0);
		if(redid!=0){
			param.put("userid", userid);
			param.put("redid", redid);
			Map<String,Object> redMap=walletMapper.queryRedAmount(param);
			giveMoney=BigDecimal.valueOf((Double)redMap.get("money"));
		}
		double needmoney=fee + tip-giveMoney.doubleValue();
		
		if(needmoney<=0){
			needmoney=0.01;
		}
		
		if (needmoney > balance) {
			return "fail";
		} else {
			Map<String, Object> temp = new HashMap<String, Object>();
			temp.put("userid", userid);
			temp.put("amount", -(needmoney));
			walletMapper.updateUserWallet(temp);// 扣除用户钱包里面的钱
			temp.put("changeTime", date);
			temp.put("changeType", type);
			temp.put("changeDesc", desc);
			temp.put("orderId", orderid);
			walletMapper.buildUserRecord(temp);// 增加用户钱包变动的记录
			temp = new HashMap<String, Object>();
			temp.put("purchaseAmount", fee+discount);
			if(fee + tip-giveMoney.doubleValue()<=0){
				temp.put("tipAmount", tip+0.01);
			}else{
				temp.put("tipAmount", tip);
			}
			temp.put("brokerid", brokerid);
			//判断经纪人钱包是否存在
			Map<String, Object> map = walletMapper.getBalance(brokerid);
			if (map == null) {
				SimpleDateFormat sdf = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				Map<String, Object> temp3 = new HashMap<String, Object>();
				temp3.put("popid", brokerid);
				temp3.put("date", sdf.format(new Date()));
				walletMapper.addBrokerWallet(temp3);
				map = walletMapper.getBalance(brokerid);
			}
			walletMapper.payToBroker(temp);// 给经纪人钱包增加相应的小费和代购费
			String desc1;
			if (type == 1) {
				desc1 = "代办";
			} else if (type == 2) {
				desc1 = "代购";
			} else {
				desc1 = "代送";
			}
			temp.put("changeDesc", desc1);
			temp.put("orderId", orderid);
			temp.put("changeTime", date);
			temp.put("brokerId", brokerid);
			walletMapper.addBrokerWalletLog(temp);// 给经纪人钱包增加相应的记录
			// 设置相应呼单为已完成
			Map<String, Object> temp2 = new HashMap<String, Object>();
			temp2.put("status", 8);
			temp2.put("orderid", orderid);
			orderMapper.updateOrderStatus(temp2);
			
			if(redid!=0){
				param.put("userid", userid);
				param.put("redid", redid);
				param.put("orderid", orderid);
				param.put("status", 2);//将优惠券改为已使用
				walletMapper.updateRed(param);
			}
			
			if(discount>0){
				Map<String,Object> pool=walletMapper.queryFundPoll("FUND_10_WAN");
				Map<String,Object> poolParam=new HashMap<String, Object>();
				poolParam.put("amount", discount);
				poolParam.put("fundCode", "FUND_10_WAN");
				walletMapper.updateActivityFundPool(poolParam);
				Map<String,Object> logParam=new HashMap<String, Object>();
				logParam.put("activityType", 0);//0表示商品折扣
				logParam.put("amount", discount);
				logParam.put("orderId", orderid);
				logParam.put("createTime", Calendar.getInstance().getTime());
				logParam.put("activityDesc", "商品折扣"+discount+"元");
				logParam.put("fundId", pool.get("fundId"));
				logParam.put("fundCode", "FUND_10_WAN");
				walletMapper.insertActivityFundPoolLog(logParam);
			}
			
			if(giveMoney.doubleValue()>0){
				if((tip+fee)<giveMoney.doubleValue()){
					giveMoney=BigDecimal.valueOf(tip+fee);
				}
				Map<String,Object> pool=walletMapper.queryFundPoll("FUND_50_WAN");
				Map<String,Object> poolParam=new HashMap<String, Object>();
				poolParam.put("amount", giveMoney.doubleValue());
				poolParam.put("fundCode", "FUND_50_WAN");
				walletMapper.updateActivityFundPool(poolParam);
				Map<String,Object> logParam=new HashMap<String, Object>();
				logParam.put("activityType", 2);//0表示商品折扣
				logParam.put("amount", giveMoney.doubleValue());
				logParam.put("orderId", orderid);
				logParam.put("createTime", Calendar.getInstance().getTime());
				logParam.put("activityDesc", "优惠券"+giveMoney.doubleValue()+"元");
				logParam.put("fundId", pool.get("fundId"));
				logParam.put("fundCode", "FUND_50_WAN");
				walletMapper.insertActivityFundPoolLog(logParam);
			}
			
			final int brokerId=brokerid;
			final int oid = orderid;
			new Thread(new Runnable() {
				public void run() {
					//推送付款成功消息
					Map<String,Object> brokerMap=popuserMapper.queryBrokerById(brokerId);
//					User user=userMapper.getUserNameById();
					JPushClient clientBroker = JPush.getBrokerJPushClient();
//					JPushClient clientUser = JPush.getUserJPushClient();
//					JPush.pushWithAlias(clientUser, "", user.getIsvAccountId());
					JPush.pushWithAlias(clientBroker, OrderCons.PAY_SUCCESS, brokerMap.get("isvAccountId").toString());
					
					Message message = new Message(OrderCons.PAY_SUCCESS, brokerId,
							MessageCons.USER_TYPE_BROKER,
							MessageCons.MESSAGE_TYPE_ORDER);
					message.setCreatetime(HelperUtil.getCurrentDate());
					message.setUpdatetime(HelperUtil.getCurrentDate());
					messageService.saveMessage(message);
					//保存进度
					OrderProgress op= new OrderProgress();
					op.setUserMsg(ProgressCons.ORDER_PAYED_MSG);
					op.setContent(ProgressCons.ORDER_PAYED_CONTENT);
					op.setOrderid(oid);
					op.setOrderStatus(OrderCons.ORDER_WAIT_EVALUATE);
					op.setCreatetime(HelperUtil.getCurrentDate());
					op.setUpdatetime(HelperUtil.getCurrentDate());
					orderProgressMapper.addOrderProgress(op);
					
					//用户通知存档
					Message usermessage = new Message(OrderCons.USER_PAY_SUCCESS, userid,
							MessageCons.USER_TYPE_USER,
							MessageCons.MESSAGE_TYPE_ORDER);
					usermessage.setCreatetime(HelperUtil.getCurrentDate());
					usermessage.setUpdatetime(HelperUtil.getCurrentDate());
					messageService.saveMessage(usermessage);
				}
			}).start();
			return "success";
		}
	}

	public Map<String, Object> getPayOrderByNo(String orderNo) {
		return walletMapper.userOrderStatus(orderNo);
	}
	
	public List<BatchWithdrawRecord> queryBatchWithdrawOrders(){
		return walletMapper.queryBatchWithdrawOrders();
	}
	
	public BatchWithdrawRecord queryBatchWithdrawOrderByOrderNo(String batchOrderNo){
		return walletMapper.queryBatchWithdrawOrderByOrderNo(batchOrderNo);
	}
	
	public List<WithdrawOrder> queryWithdrawOrdersByBatchNo(String batchOrderNo){
		return walletMapper.queryWithdrawOrdersByBatchNo(batchOrderNo);
	}
	public static void main(String[] args) {
		int redid=0;
		System.out.println(!"0".equals(redid));
	}
}
